import functools
import config
from flask import request
from app import redis_pool
from app.utils.response_format import resp_json, RET, error_map


def login_user_data(view_func):
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):
        if config.OPEN_AUTH:
            # 判断用户登录状态是否保持
            user_id = request.headers.get('auth_token')
            ip = request.remote_addr

            if not user_id:
                return resp_json(status=RET.ROLEERR, message=error_map[RET.ROLEERR])

            # 校验ip
            ip_list = config.IP_WHITE_LIST
            if '*' not in ip_list:
                if ip not in ip_list:
                    return resp_json(status=RET.IPERR, message=error_map[RET.IPERR])
            
            # 校验用户是否过期
            res = redis_pool.get_key(user_id)
            if res != 'userId':
                return resp_json(status=RET.ROLEERR, message=error_map[RET.ROLEERR])
            redis_pool.set_key(user_id, 'userId')
            redis_pool.expire(user_id, second=config.ROLE_EXPIRE_TIME)
        return view_func(*args, **kwargs)
    return wrapper